package com.cai.baselibrary.net.response

import com.google.gson.*
import com.google.gson.internal.bind.DateTypeAdapter
import com.google.gson.stream.JsonReader
import java.io.Reader
import java.lang.reflect.Type
import java.util.*

object Convert {
    private fun create(): Gson {
        return GsonHolder.gson
    }

    private object GsonHolder {
        val gson = GsonBuilder()
            .setPrettyPrinting()
            .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .registerTypeAdapter(Date::class.java, DateTypeAdapter())
            .create()
    }

    @Throws(JsonIOException::class, JsonSyntaxException::class)
    fun <T> fromJson(json: String?, type: Class<T>?): T {
        return create().fromJson(json, type)
    }

    fun <T> fromJson(json: String?, type: Type?): T {
        return create().fromJson(json, type)
    }

    @Throws(JsonIOException::class, JsonSyntaxException::class)
    fun <T> fromJson(reader: JsonReader?, typeOfT: Type?): T {
        return create().fromJson(reader, typeOfT)
    }

    @Throws(JsonSyntaxException::class, JsonIOException::class)
    fun <T> fromJson(json: Reader?, classOfT: Class<T>?): T {
        return create().fromJson(json, classOfT)
    }

    @Throws(JsonIOException::class, JsonSyntaxException::class)
    fun <T> fromJson(json: Reader?, typeOfT: Type?): T {
        return create().fromJson(json, typeOfT)
    }

    fun toJson(src: Any?): String? {
        return create().toJson(src)
    }

    fun toJson(src: Any?, typeOfSrc: Type?): String? {
        return create().toJson(src, typeOfSrc)
    }

    fun formatJson(json: String?): String? {
        return try {
            val jp = JsonParser()
            val je = jp.parse(json)

       create().toJson(je)
        } catch (e: Exception) {
            json
        }
    }

    fun formatJson(src: Any?): String? {
        return try {
            val jp = JsonParser()
            val je = jp.parse(toJson(src))
            create().toJson(je)
        } catch (e: Exception) {
            e.message
        }
    }
}